package com.f6.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import com.f6.common.constants.CommonCanstants;
import com.f6.common.service.CommonService;
import com.f6.common.service.SearchService;
import com.f6.common.service.WxbService;
import com.f6.common.util.AdvancedUtil;
import com.f6.common.util.EmojiFilter;
import com.f6.common.util.MessageUtil;
import com.f6.model.AppStation;
import com.f6.model.CarModel;
import com.f6.model.CarTmodel;
import com.f6.model.Fenxiang;
import com.f6.model.Puser;
import com.f6.model.SNSUserInfo;
import common.weixinutils.response.Article;
import common.weixinutils.response.NewsMessage;
import common.weixinutils.response.TextMessage;
  
/**
 * 核心服务类  
 * @author pengsong
 *服务号服务类
 */
public class CoreService {
	/**
	 * 处理微信发来的请求
	 * 换行符仍然是"\n"
	 * @param request
	 * @return
	 */
	public static String processRequest(HttpServletRequest request,String appid) {
    	/*
		String respMessage = null;
		try {
			// 默认返回的文本消息内容
			String respContent = "";

			// xml请求解析
			Map<String, String> requestMap = MessageUtil.parseXml(request);
			
			String appId = requestMap.get("AppId");
			if(appId != null && !"".equals(appId)){
				appid = appId;
			}

			// 发送方帐号（open_id）
			String fromUserName = requestMap.get("FromUserName");
			// 公众帐号
			String toUserName = requestMap.get("ToUserName");
			// 消息类型
			String msgType = requestMap.get("MsgType");
			String Encrypt = requestMap.get("Encrypt");
			
			if(Encrypt != null && !"".equals(Encrypt)){
				
			}
			
			System.out.println("Encrypt======="+Encrypt);

			// 回复文本消息
			TextMessage textMessage = new TextMessage();
			textMessage.setToUserName(fromUserName);
			textMessage.setFromUserName(toUserName);
			//两种获取整形时间的方法。 获取到的结果表示当时时间距离1970年1月1日0时0分0秒0毫秒的毫秒数。公众平台api中消息创建时间CreateTime，它表示1970年1月1日0时0分0秒至消息创建时所间隔的秒数，注意是间隔的秒数，不是毫秒数！
			//long longTime1 = System.currentTimeMillis();  
		    //long longTime2 = new java.util.Date().getTime();  
			textMessage.setCreateTime(new Date().getTime());
			textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
			textMessage.setFuncFlag(0);

			System.out.println("============启动==============微信事件=======");
			System.out.println("最开始的事件类型为:"+msgType);
			//获取用户信息
			
			AccessToken at = TokenThread.accessToken;
			SNSUserInfo snsUserInfo = AdvancedUtil.getSNSUserInfo(at.getToken(), fromUserName);
			// 文本消息
			String msgId = requestMap.get("MsgId");
			if(msgType != null){
				if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {
					String content = requestMap.get("Content");
					CommonService.saveWxDialog(toUserName, fromUserName, msgType, toUserName, content, msgId, null, null, null, null, 0, 0,null,null,null);
					boolean judgeVin = SearchService.isVinCode(content.trim());
					if(judgeVin){
						CarTmodel carTmodel = SearchService.getCarTmodelByVin(content.trim());
						CarModel carModel = SearchService.getCarModelByVIN(content.trim());
						respContent = "F6养车网诚心为您服务\n\n";
						if(carModel != null && carModel.getMid() != null){
							respContent += "您的爱车为："+carModel.getBrandName()+" "+carModel.getVehicleSystem()+" "+carModel.getExhaustVolume()+" "+carModel.getYear()+"\n\n";
						}
						if(carTmodel != null && carTmodel.getMid() != null){
							respContent += "-----变速箱信息-----\n";
							respContent += "变速箱型号："+carTmodel.getTmodel()+"\n\n";
							respContent += "原OEM油配件号："+carTmodel.getOilOem()+"\n\n";
							respContent += "手动换油量："+carTmodel.getManualOilCap()+"\n\n";
							respContent += "机器换油量："+carTmodel.getMachineOilCap()+"\n\n";
							if(carTmodel.getIsReplace() != null){
								if(carTmodel.getIsReplace().equals("0")){
									respContent += "是否更换滤网：否\n\n";
								}else{
									respContent += "是否更换滤网：是\n\n";
								}
							}
							respContent += "市场指导价："+carTmodel.getPriceMarket()+"元/升\n\n";
							if(carTmodel.getOilPrice4s() == null){
								respContent += "4s店油品价格：暂无\n\n";
							}else{
								respContent += "4s店油品价格："+carTmodel.getOilPrice4s()+"\n\n";
							}
							if(carTmodel.getPackagePrice4s() == null){
								respContent += "4s店套餐价：暂无\n\n";
							}else{
								respContent += "4s店套餐价："+carTmodel.getPackagePrice4s()+"\n\n";
							}
						}
						if(carModel != null && carModel.getMid() != null){
							respContent += "-----车型信息-----\n";
							respContent += "<a href='http://weixin.carzone.cn/search?mid="+carModel.getMid()+"&type=3'>点击查看相关联配件信息</a>\n\n";
				    		respContent += "厂家名称："+carModel.getManufacturerName()+"\n\n";
				    		respContent += "品牌："+carModel.getBrandName()+"\n\n";
				    		respContent += "车型："+carModel.getVehicleSystem()+"\n\n";
				    		respContent += "版本："+carModel.getSalesVersion()+"\n\n";
				    		respContent += "年款："+carModel.getYear()+"\n\n";
				    		respContent += "生产年份："+carModel.getMadeYear()+"\n\n";
				    		respContent += "车辆类型："+carModel.getVehicleCategory()+"\n\n";
				    		respContent += "停产年份："+carModel.getStopProductionYear()+"\n\n";
				    		respContent += "国标："+carModel.getCountry()+"\n\n";
				    		respContent += "发动机型号："+carModel.getEngineType()+"\n\n";
				    		respContent += "发动机缸数："+carModel.getCylindersNumber()+"\n\n";
				    		respContent += "发动机："+carModel.getEngineDesc()+"\n\n";
				    		respContent += "底盘号："+carModel.getFloorNo()+"\n\n";
				    		respContent += "气缸容积："+carModel.getCylinderVolume()+"\n\n";
				    		respContent += "排量："+carModel.getExhaustVolume()+"\n\n";
				    		respContent += "燃油类型："+carModel.getFuelType()+"\n\n";
				    		respContent += "燃油标号："+carModel.getFuelTag()+"\n\n";
				    		respContent += "排放标准："+carModel.getEmissionStandars()+"\n\n";
				    		respContent += "功率/转速："+carModel.getPowerSpeed()+"\n\n";
				    		respContent += "长："+carModel.getLength()+"\n\n";
				    		respContent += "宽："+carModel.getWidth()+"\n\n";
				    		respContent += "高："+carModel.getHeight()+"\n\n";
				    		respContent += "轴距："+carModel.getWheelbase()+"\n\n";
				    		respContent += "前轮距："+carModel.getFrontTread()+"\n\n";
				    		respContent += "后轮距："+carModel.getRearTread()+"\n\n";
				    		respContent += "油箱容积："+carModel.getRearTread()+"\n\n";
				    		respContent += "整备质量："+carModel.getKerbMass()+"\n\n";
				    		respContent += "车身形式："+carModel.getBodyForm()+"\n\n";
				    		respContent += "车门数："+carModel.getDoorNumber()+"\n\n";
				    		respContent += "座位数："+carModel.getSeatNumber()+"\n\n";
				    		respContent += "气缸排列形式："+carModel.getCylinderArrangement()+"\n\n";
				    		respContent += "扭矩/转速："+carModel.getPowerSpeed()+"\n\n";
				    		respContent += "变速器描述："+carModel.getTransmissionDesc()+"\n\n";
				    		respContent += "档位数："+carModel.getFileNumber()+"\n\n";
				    		respContent += "驱动形式："+carModel.getDriveForm()+"\n\n";
				    		respContent += "前悬挂系统："+carModel.getFrontSuspedSys()+"\n\n";
				    		respContent += "后悬挂系统："+carModel.getRearSuspedSys()+"\n\n";
				    		respContent += "制动类型："+carModel.getBrakeType()+"\n\n";
				    		respContent += "转向助力类型："+carModel.getPowerSteeringType()+"\n\n";
				    		respContent += "前轮胎规格："+carModel.getFrontTireSpec()+"\n\n";
				    		respContent += "后轮胎规格："+carModel.getRearTireSpec()+"\n\n";
				    		respContent += "轮毂规格："+carModel.getHubSpec();
						}
					}else{
						*/
						/*if(CommonCanstants.app_wx_sid_chexiaojian.equals(toUserName)){
							if("1".equals(content.trim())){
								respContent = "价值8800元微营销课程\n";
								respContent += "请您到下方地址自助下载：\n";
								respContent += "<a href='http://pan.baidu.com/s/1c0BILm4'>http://pan.baidu.com/s/1c0BILm4</a>\n\n";
								respContent += "==================\n";
								respContent += "小贱多次重新下载，都是可以正常解压的\n";
								respContent += "后来发现无法解压的小伙伴多是用的360压缩、好压、2345压缩等解压软件，可能是兼容\n";
								respContent += "性有问题，导致解压错误。\n";
								respContent += "请大家使用最正宗的解压软件【winrar】，自行百度下载\n";
								respContent += "能解压，可能是下载过程出错，网盘会抽疯，小贱很无奈~麻烦您重新下载啦\n";
							}else if("2".equals(content.trim())){
								respContent = "全网最牛SEO完整视频\n";
								respContent += "请您到下方地址自助下载：\n";
								respContent += "<a href='http://pan.baidu.com/s/1c0yl9gk'>http://pan.baidu.com/s/1c0yl9gk</a>\n\n";
								respContent += "==================\n";
								respContent += "小贱多次重新下载，都是可以正常解压的\n";
								respContent += "后来发现无法解压的小伙伴多是用的360压缩、好压、2345压缩等解压软件，可能是兼容\n";
								respContent += "性有问题，导致解压错误。\n";
								respContent += "请大家使用最正宗的解压软件【winrar】，自行百度下载\n";
								respContent += "能解压，可能是下载过程出错，网盘会抽疯，小贱很无奈~麻烦您重新下载啦\n";
							}else if("3".equals(content.trim())){
								respContent = "大咖演讲及投资秘诀分享\n";
								respContent += "（马云、徐小平等）\n";
								respContent += "请您到下方地址自助下载：\n";
								respContent += "<a href='http://yunpan.cn/OcFhtRiqb8iGwQ'>http://yunpan.cn/OcFhtRiqb8iGwQ</a>\n";
								respContent += "（提取码：646e）\n\n";
								respContent += "==================\n";
								respContent += "小贱多次重新下载，都是可以正常解压的\n";
								respContent += "后来发现无法解压的小伙伴多是用的360压缩、好压、2345压缩等解压软件，可能是兼容\n";
								respContent += "性有问题，导致解压错误。\n";
								respContent += "请大家使用最正宗的解压软件【winrar】，自行百度下载\n";
								respContent += "能解压，可能是下载过程出错，网盘会抽疯，小贱很无奈~麻烦您重新下载啦\n";
							}else if("4".equals(content.trim())){
								respContent = "哈佛公开课之颠覆思想的七个演讲\n";
								respContent += "请您到下方地址自助下载：\n";
								respContent += "<a href='http://pan.baidu.com/s/1gdCY6x9'>http://pan.baidu.com/s/1gdCY6x9</a>\n\n";
								respContent += "==================\n";
								respContent += "小贱多次重新下载，都是可以正常解压的\n";
								respContent += "后来发现无法解压的小伙伴多是用的360压缩、好压、2345压缩等解压软件，可能是兼容\n";
								respContent += "性有问题，导致解压错误。\n";
								respContent += "请大家使用最正宗的解压软件【winrar】，自行百度下载\n";
								respContent += "能解压，可能是下载过程出错，网盘会抽疯，小贱很无奈~麻烦您重新下载啦\n";
							}else if("5".equals(content.trim())){
								respContent = "男士爱看的电影\n";
								respContent += "请您到下方地址自助下载：\n";
								respContent += "<a href='http://pan.baidu.com/s/1dD2nr9J'>http://pan.baidu.com/s/1dD2nr9J</a>\n\n";
								respContent += "==================\n";
								respContent += "小贱多次重新下载，都是可以正常解压的\n";
								respContent += "后来发现无法解压的小伙伴多是用的360压缩、好压、2345压缩等解压软件，可能是兼容\n";
								respContent += "性有问题，导致解压错误。\n";
								respContent += "请大家使用最正宗的解压软件【winrar】，自行百度下载\n";
								respContent += "能解压，可能是下载过程出错，网盘会抽疯，小贱很无奈~麻烦您重新下载啦\n";
							}else if("6".equals(content.trim())){
								respContent = "独家音乐下载\n";
								respContent += "请您到下方地址自助下载：\n";
								respContent += "<a href='http://yun.baidu.com/s/1pJOUleF'>http://yun.baidu.com/s/1pJOUleF</a>\n\n";
								respContent += "==================\n";
								respContent += "小贱多次重新下载，都是可以正常解压的\n";
								respContent += "后来发现无法解压的小伙伴多是用的360压缩、好压、2345压缩等解压软件，可能是兼容\n";
								respContent += "性有问题，导致解压错误。\n";
								respContent += "请大家使用最正宗的解压软件【winrar】，自行百度下载\n";
								respContent += "能解压，可能是下载过程出错，网盘会抽疯，小贱很无奈~麻烦您重新下载啦\n";
							}
						}
						if(CommonCanstants.app_wx_sid_chexiaojian.equals(toUserName)){
							if("".equals(respContent)){
								//首先判断是否存在在文本文件中
								Map map = SearchService.getkeysMaps();
								if(map != null && map.size() > 0){
									String value = (String) map.get(content.trim());
									if(value != null){
										respContent = value;
									}else{
										respContent = CommonService.getMsgReply(content.trim());
									}
									
									else{
										List<AccInfo> accInfos = SearchService.getAccInfoByList(content.trim(),fromUserName,0);
								    	if(accInfos != null && accInfos.size() > 0){
								    		List<Article> articleList = SearchService.getArticlesByList(accInfos,content);
									    	
									    	NewsMessage newsMessage = new NewsMessage();
							                newsMessage.setToUserName(fromUserName);  
							                newsMessage.setFromUserName(toUserName);  
							                newsMessage.setCreateTime(new Date().getTime());  
							                newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);  
							                newsMessage.setFuncFlag(0);
							                
						                	newsMessage.setArticleCount(articleList.size());  
						                    newsMessage.setArticles(articleList);  
						                    respMessage = MessageUtil.newsMessageToXml(newsMessage);
						                    return respMessage;
								    	}else{
								    		respContent = CommonService.getMsgReply(content.trim());
								    	}
									}
								}else{
									respContent = CommonService.getMsgReply(content.trim());
								}
								
							}
						}else{
							AppStation appStation = CommonService.getAppStation(null,toUserName);
							if(appStation != null){
								//首先判断是否关键词
								respContent = WxbService.getKeyAutoReply(appStation.getWxAppId(),content.trim());
								if(respContent != null && !"".equals(respContent)){
									//do nothing
								}else{
									respContent = WxbService.getAutoReply(appStation.getWxAppId());
									if(respContent != null && !"".equals(respContent)){
										//do nothing
									}else{
										respContent ="您的消息我们已收到，稍后会有专人和您联系，若未能及时回复您，请拨打我们的服务热线：400-025-1166。";
									}
								}
							}else{
								respContent ="您的消息我们已收到，稍后会有专人和您联系，若未能及时回复您，请拨打我们的服务热线：400-025-1166。";
							}
						}
					}
				}    
				// 图片消息
				else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)) {
					String picUrl = requestMap.get("PicUrl");
					CommonService.saveWxDialog(toUserName, fromUserName, msgType, toUserName, null, msgId, null, null, picUrl, null, 0, 0,null,null,null);
					if(CommonCanstants.app_wx_sid_chexiaojian.equals(toUserName)){
						respContent = "300套绝世PPT模板\n\n";
						respContent	+= "请您到下方地址自助下载：\n\n";
						respContent += "<a href='http://pan.baidu.com/s/1hqzzt6O'>http://pan.baidu.com/s/1hqzzt6O</a>\n\n";
						respContent += "==================\n";
						respContent += "小贱多次重新下载，都是可以正常解压的\n";
						respContent += "后来发现无法解压的小伙伴多是用的360压缩、好压、2345压缩等解压软件，可能是兼容\n";
						respContent += "性有问题，导致解压错误。\n";
						respContent += "请大家使用最正宗的解压软件【winrar】，自行百度下载\n";
						respContent += "能解压，可能是下载过程出错，网盘会抽疯，小贱很无奈~麻烦您重新下载啦\n";
					}else{
						respContent = "谢谢您的分享！";
					}
					
				}
				// 地理位置消息
				else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION_1)) {
					respContent ="您的消息我们已收到，稍后会有专人和您联系，若未能及时回复您，请拨打我们的服务热线：400-025-1166。";
				}
				// 链接消息
				else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)) {
					String title = requestMap.get("Title");
					String description = requestMap.get("Description");
					String url = requestMap.get("Url");
					CommonService.saveWxDialog(toUserName, fromUserName, msgType, toUserName, null, msgId, null, null, null, null, null, null,title,description,url);
					respContent = "谢谢您的分享！";
				}
				// 音频消息
				else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)) {
					String mediaId = requestMap.get("MediaId");
					String format = requestMap.get("Format");
					CommonService.saveWxDialog(toUserName, fromUserName, msgType, toUserName, null, msgId, mediaId, format, null, null, 0, 0, null, null, null);
					respContent = "谢谢您的分享！";
				}
				// 事件推送
				else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {
					// 事件类型
					String eventType = requestMap.get("Event");
					// 创建图文消息  
//	                NewsMessage newsMessage = new NewsMessage();  
//	                newsMessage.setToUserName(fromUserName);  
//	                newsMessage.setFromUserName(toUserName);  
//	                newsMessage.setCreateTime(new Date().getTime());  
//	                newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);  
//	                newsMessage.setFuncFlag(0); 
					System.out.println("事件类型========"+eventType);
					// 订阅
					if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {
						System.out.println(requestMap);
						String EventKey = requestMap.get("EventKey");
						if(EventKey.contains("qrscene_")){
							int index = EventKey.indexOf("_");
							EventKey = EventKey.substring(index+1,EventKey.length());
						}
						if(EventKey.contains("vin") || EventKey.contains("car") || EventKey.contains("emp") || EventKey.contains("msg")){
							//通过扫码关注vin过来的
							String[] arr = EventKey.split("-");
							AppStation appStation = CommonService.getAppStation(null,toUserName);
							if(appStation != null){
								String appsecret = CommonService.getappsercet(appStation.getWxAppId());
								String accessToken = CommonService.getToken(appStation.getWxAppId(),appsecret);
								SNSUserInfo snsUser = AdvancedUtil.getSNSUserInfo(accessToken, fromUserName);
								String userName = EmojiFilter.filterEmoji(snsUser.getNickname());
								if("vin".equals(arr[0])){
									CarModel carModel = SearchService.getCarModelByVIN(arr[1]);
									if(carModel != null && carModel.getMid() != null){
										CommonService.saveUserAndCar(userName, userName, fromUserName, appStation.getWxAppId(), carModel.getMid()+"", arr[1], 
												carModel.getOnMarketYear(), carModel.getOnMarketMonth(), carModel.getBrandName(), carModel.getVehicleSystem(), carModel.getBrandName()+" "+carModel.getVehicleSystem(), 
												carModel.getBrandName()+" "+carModel.getOnMarketMonth()+"年"+carModel.getOnMarketMonth()+"月 "+carModel.getTransmissionDesc()+" "+carModel.getExhaustVolume());
										respContent = "恭喜您，你通过VIN："+arr[1]+"绑定"+carModel.getBrandName()+" "+carModel.getVehicleSystem()+"成功，赶快点击下面菜单享受服务吧！";
									}else{
										respContent = "绑定车型失败，请检查VIN是否正确！";
									}
									
									//判断用户是否存在，不存在则创建
								}else if("car".equals(arr[0])){
									//通过车型id扫码绑定车型
									CarModel carModel = SearchService.getCarModelByMid(arr[1]);
									if(carModel != null && carModel.getMid() != null){
										CommonService.saveUserAndCar(userName, userName, fromUserName, appStation.getWxAppId(), carModel.getMid()+"", arr[1], 
												carModel.getOnMarketYear(), carModel.getOnMarketMonth(), carModel.getBrandName(), carModel.getVehicleSystem(), carModel.getBrandName()+" "+carModel.getVehicleSystem(), 
												carModel.getBrandName()+" "+carModel.getOnMarketMonth()+"年"+carModel.getOnMarketMonth()+"月 "+carModel.getTransmissionDesc()+" "+carModel.getExhaustVolume());
										respContent = "恭喜您，你通过选择车型："+carModel.getBrandName()+" "+carModel.getVehicleSystem()+"绑定车型成功，赶快点击下面菜单享受服务吧！";
									}else{
										respContent = "绑定车型失败，请检查车型是否正确！";
									}
									
									
								}else if("emp".equals(arr[0])){
									String empId = arr[1];
									JSONObject jsonObject=WxbService.savePemployeeById(empId, appStation.getWxAppId(), fromUserName);
									if(jsonObject.get("result").toString().equals("success")){
										respContent = "绑定发送服务消息成功！";
										
									}else{
										
										respContent = jsonObject.get("detail").toString();
									}
									
								}else if("msg".equals(arr[0])){
									String userId = arr[1];
									WxbService.saveUserOpenId(userId, fromUserName);
									respContent = "绑定接受服务消息成功！";
								}
							}
						}else if(EventKey.equals("EMPREG")){	//F6 portal员工注册
							respContent = "请点击<a href='http://121.40.65.65:9010/toEmpRegister?openId="+fromUserName+"'>进行员工注册</a>";
						}else if(EventKey.equals("WXADD")){	//F6 portal意向客户添加
							respContent = "请点击<a href='http://121.40.65.65:9010/toWeiXinAddIntentMember?openId="+fromUserName+"'>意向客户添加</a>";
						}else if(EventKey.equals("MBWX")){	//会员店微信验证
							respContent = "请点击<a href='http://121.40.65.65:9010/validateMemberWeiXin?openId="+fromUserName+"'>会员店微信验证</a>";
						}else if(EventKey.equals("KSWX")){	//中心站微信验证
							respContent = "请点击<a href='http://121.40.65.65:9010/validateKsWeiXin?openId="+fromUserName+"'>中心站微信验证</a>";
						}else{
							//是否是车小贱
							if(CommonCanstants.app_wx_sid_chexiaojian.equals(toUserName)){
//		                    	respContent += "价值8800元微营销课程\n";
//		                    	respContent += "请回复：1\n\n";
//		                    	respContent += "全网最牛SEO完整视频\n";
//		                    	respContent += "请回复：2\n\n";
//		                    	respContent += "大咖演讲及投资秘诀分享\n";
//		                    	respContent += "（马云、徐小平等）\n";
//		                    	respContent += "请回复：3\n\n";
//		                    	respContent += "哈佛公开课之颠覆思想的七个演讲\n";
//		                    	respContent += "请回复：4\n\n";
//		                    	respContent += "男士爱看的电影\n";
//		                    	respContent += "请回复：5\n\n";
//		                    	respContent += "独家音乐下载\n";
//		                    	respContent += "请回复：6\n\n";
//		                    	respContent += "【想聊天？请任意回复】\n\n";
//		                    	respContent += "点击【小贱趴】带你进入一个牛逼的世界！\n\n";
								
								//进入我要代言页面
		                    	List<Article> articleList = new ArrayList<Article>();
		                    	Article article = new Article();
		                    	article.setUrl("http://mp.weixin.qq.com/s?__biz=MzAxMjcyNTQ5Ng==&mid=402184459&idx=1&sn=ff6a3457ce97fb3386b79c7c5637b584&key=ac89cba618d2d976753f23ac6d07de6edf8f2c8bab1d7ba670f4594d7a5fa5221bc00ceab618fb2c02ff85af45fae183&ascene=0&uin=MjA5NDYyNDE1&devicetype=iMac+MacBookPro9%2C2+OSX+OSX+10.11.1+build(15B42)&version=11020201&pass_ticket=gmA%2F9qJqoLYHt%2B9qqq2vMeENXDYobVzKheSfPo411v8%3D");
	                        	article.setTitle("【圣诞任务卡】使用攻略！ ！ ！");  
	                        	article.setPicUrl("http://f6image.b0.upaiyun.com/wxb/shengdan1.jpg");
	                        	article.setDescription("【圣诞神秘大礼】机不可失，速来领取。");
		                        articleList.add(article); 
		                        
		                        NewsMessage newsMessage = new NewsMessage();  
				                newsMessage.setToUserName(fromUserName);  
				                newsMessage.setFromUserName(toUserName);  
				                newsMessage.setCreateTime(new Date().getTime());  
				                newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);  
				                newsMessage.setFuncFlag(0);
				                
			                	newsMessage.setArticleCount(articleList.size());  
			                    newsMessage.setArticles(articleList);  
			                    respMessage = MessageUtil.newsMessageToXml(newsMessage);
			                    return respMessage;
							}else{
								Puser puser = CommonService.getPuserById(EventKey);
								//获得扫描传的值，该值为谁传过来的openIdx
								//判断fromUserName是否存在puser中
								String appsecret = CommonService.getappsercet(puser.getWxAppId());
								
								String accessToken = CommonService.getToken(puser.getWxAppId(),appsecret);
								SNSUserInfo snsUser = AdvancedUtil.getSNSUserInfo(accessToken, fromUserName);
								if(snsUser != null){
									boolean judgePuser = CommonService.judgePuser(puser.getWxAppId(), fromUserName);
									System.out.println("该用户是否存在："+judgePuser);
									if(!judgePuser){
										//则存储
										CommonService.savePuserForId(snsUser.getNickname(), snsUser.getNickname(), fromUserName, puser.getWxAppId(), snsUser.getHeadImgUrl());
										//判断是否已经存在用户分享表里了
										boolean judgeAuserFenxiang = CommonService.judgeAuserFenxiang(puser.getWxOpenId(), fromUserName, puser.getWxAppId());
										if(!judgeAuserFenxiang){
											//存储该信息
											CommonService.saveAuserFenxiang(puser.getWxOpenId(), fromUserName, puser.getWxAppId(),snsUser.getHeadImgUrl());
										}
									}
									
								}
								AppStation appStation = CommonService.getAppStation(null,toUserName);
								if(appStation != null){
									respContent = WxbService.getScribeReply(appStation.getWxAppId());
									if(respContent != null && !"".equals(respContent)){
										//do nothing
									}else{
										respContent = "亲，终于等到你了！";
									}
								}else{
									respContent = "亲，终于等到你了！";
								}
								
//								AppStation appStation = CommonService.getAppStation(puser.getWxAppId(),null);
//								if(appStation != null){
//									respContent = "您已关注["+appStation.getAppName()+"]，点击菜单中的“我要代言”可生成二维码转发到朋友圈等或发送给好友邀请朋友关注。";
//								}else{
//									respContent = "亲，终于等到你了！";
//								}
							}
						}
					}else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {
						// 事件KEY值，与创建自定义菜单时指定的KEY值对应  
	                    String eventKey = requestMap.get("EventKey");  
	                    System.out.println("事件key========"+eventKey);
	                    if (eventKey.equals("11")) {
	                    	//进入我要代言页面
	                    	//respContent = "欢迎您，康众员工功能即将开放";
	                    	List<Article> articleList = new ArrayList<Article>();
	                    	Article article = new Article();
	                       
	                        // 将图片置为空  
	                        //article.setPicUrl("http://cdn.carzone.cn/images/oa.png");  
	                        if(CommonCanstants.app_wx_sig_jiamusi.equals(toUserName)){
	                        	article.setUrl("http://weixin.f6car.com/actAppStationForNWW?openId="+fromUserName+"&appid="+appid);
	                        	 article.setTitle("我要代言，不一样的风采");  
	 	                        // 图文消息中可以使用QQ表情、符号表情  
	 	                        article.setDescription("通过代言转发，进入代言概况查看奖品信息!");  
	                        }else if(CommonCanstants.app_wx_sid_chexiaojian.equals(toUserName)){
	                        	article.setUrl("http://weixin.f6car.com/actAppStationForChexiaojian?openId="+fromUserName+"&appid="+appid);
	                        	article.setTitle("【圣诞任务卡】加冕人气王，圣诞有惊喜！");  
	                        	article.setPicUrl("http://f6image.b0.upaiyun.com/wxb/lanse.jpg");
	 	                        // 图文消息中可以使用QQ表情、符号表情  
	 	                        //article.setDescription("通过代言转发，进入代言概况查看奖品信息!");  
	                        }else{
	                        	article.setUrl("http://weixin.f6car.com/actAppStation?openId="+fromUserName+"&appid="+appid);
	                        	 article.setTitle("我要代言，不一样的风采");  
	 	                        // 图文消息中可以使用QQ表情、符号表情  
	 	                        article.setDescription("通过代言转发，进入代言概况查看奖品信息!");  
	                        }
	                          
	                        articleList.add(article); 
	                        
	                        NewsMessage newsMessage = new NewsMessage();  
			                newsMessage.setToUserName(fromUserName);  
			                newsMessage.setFromUserName(toUserName);  
			                newsMessage.setCreateTime(new Date().getTime());  
			                newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);  
			                newsMessage.setFuncFlag(0);
			                
		                	newsMessage.setArticleCount(articleList.size());  
		                    newsMessage.setArticles(articleList);  
		                    respMessage = MessageUtil.newsMessageToXml(newsMessage);
		                    return respMessage;
	                    }else if (eventKey.equals("12")) {
	                    	//代言概况
	                    	//根据openid 与appid获取
	                    	//获取appid
	                    	AppStation appStation = CommonService.getAppStation(null,toUserName);
	                    	Integer totalCount = CommonService.getTotalFenxiang(fromUserName, appStation.getWxAppId());
	                    	Fenxiang fenxiang = CommonService.getTotalOrder(fromUserName, CommonCanstants.appId);
	                    	if(CommonCanstants.app_wx_sig_shuangniu.equals(toUserName)){
	                    		if(fenxiang != null && fenxiang.getOrdernum() != null && fenxiang.getFenxiangnum() != null){
	                        		Integer ordernum = Integer.parseInt(fenxiang.getOrdernum().trim());
	                        		Integer fenxiangnum = Integer.parseInt(fenxiang.getFenxiangnum().trim());
	                        		String goods = "无";
	                        		if(fenxiangnum.intValue() > 12 && fenxiangnum.intValue() <= 22){
	                        			goods = "半价洗车一次";
	                        		}else if(fenxiangnum.intValue() > 22 && fenxiangnum.intValue() <= 30){
	                        			goods = "享2元洗车一次";
	                        		}else if(fenxiangnum.intValue() > 30){
	                        			goods = "免费送500分钟话费";
	                        			
	                        			if(ordernum.intValue() == 3){
		                        			goods = "任意维保服务免工时费一次";
		                        		}else if(ordernum.intValue() == 2){
		                        			goods = "免费小保养一次";
		                        		}else if(ordernum.intValue() == 1){
		                        			goods = "免费变速箱养护一次";
		                        		}
	                        		}
	                        		
	                        		respContent = "目前您的人气是"+totalCount+"人，排名是"+fenxiang.getOrdernum()+"，奖品为"+goods+"，请继续努力哦!";
	                        	}else{
	                        		respContent = "目前您的人气是"+totalCount+"人，排名与奖品无，请继续努力哦~";
	                        	}
	                    	}else if(CommonCanstants.app_wx_sig_jiamusi.equals(toUserName)){
	                    		if(fenxiang != null && fenxiang.getOrdernum() != null && fenxiang.getFenxiangnum() != null){
	                        		Integer ordernum = Integer.parseInt(fenxiang.getOrdernum().trim());
	                        		String goods = "无";
	                        		if(ordernum.intValue() == 1){
	                        			goods = "手机一部 华为1500元";
	                        		}else if(ordernum.intValue() == 2){
	                        			goods = "手机一部 华为1500元";
	                        		}else if(ordernum.intValue() == 3){
	                        			goods = "手机一部 华为1500元";
	                        		}else if(ordernum.intValue() == 4){
	                        			goods = "手机一部 华为899元";
	                        		}else if(ordernum.intValue() == 5){
	                        			goods = "手机一部 华为899元";
	                        		}else if(ordernum.intValue() == 6){
	                        			goods = "手机一部 华为899元";
	                        		}else if(ordernum.intValue() == 7){
	                        			goods = "手机一部 华为899元";
	                        		}else if(ordernum.intValue() == 8){
	                        			goods = "手机一部 华为899元";
	                        		}else{
	                        			goods = "7-12专家电话指导您做地";
	                        		}
	                        		
	                        		respContent = "目前您的人气是"+totalCount+"人，排名是"+fenxiang.getOrdernum()+"，奖品为"+goods+"，请继续努力哦!";
	                        	}else{
	                        		respContent = "目前您的人气是"+totalCount+"人，排名与奖品无，请继续努力哦~";
	                        	}
	                    	}else{
	                    		respContent = "目前通过您的代言关注人数为"+totalCount+"人，代言奖品可以到店去领取，继续努力哦!";
	                    	}
	                    }else if (eventKey.equals("che21")) {
	                    	respContent = "价值8800元微营销课程\n";
	                    	respContent += "请回复：1\n\n";
	                    	respContent += "全网最牛SEO完整视频\n";
	                    	respContent += "请回复：2\n\n";
	                    	respContent += "大咖演讲及投资秘诀分享\n";
	                    	respContent += "（马云、徐小平等）\n";
	                    	respContent += "请回复：3\n\n";
	                    	respContent += "哈佛公开课之颠覆思想的七个演讲\n";
	                    	respContent += "请回复：4\n\n";
	                    	respContent += "男士爱看的电影\n";
	                    	respContent += "请回复：5\n\n";
	                    	respContent += "音乐下载\n";
	                    	respContent += "请回复：6\n\n";
	                    	
	                    }else if (eventKey.equals("daiyan")) {
	                    	//进入我要代言页面
	                    	//respContent = "欢迎您，康众员工功能即将开放";
	                    	List<Article> articleList = new ArrayList<Article>();
	                    	Article article = new Article();
	                       
	                        // 将图片置为空  
	                    	article.setUrl("http://weixin.f6car.com/speakFrame1.0?appid="+appid+"&openId="+fromUserName);
	                    	article.setTitle("我要代言，不一样的风采");  
	                        // 图文消息中可以使用QQ表情、符号表情  
	                        article.setDescription("通过代言转发，进入代言概况查看奖品信息!");
	                        articleList.add(article); 
	                        
	                        NewsMessage newsMessage = new NewsMessage();  
			                newsMessage.setToUserName(fromUserName);  
			                newsMessage.setFromUserName(toUserName);  
			                newsMessage.setCreateTime(new Date().getTime());  
			                newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);  
			                newsMessage.setFuncFlag(0);
			                
		                	newsMessage.setArticleCount(articleList.size());  
		                    newsMessage.setArticles(articleList);  
		                    respMessage = MessageUtil.newsMessageToXml(newsMessage);
		                    return respMessage;
	                    }
					}else if (eventType.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)) {
						respContent = "您发送的是地理位置消息！";
						String Latitude = requestMap.get("Latitude");	//纬度
						String Longitude = requestMap.get("Longitude");	//经度
						System.out.println("纬度1是==="+Latitude+"  经度1是==="+Longitude);
						
						return "";
					}// 取消订阅
					else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {
						// TODO 取消订阅后用户再收不到公众号发送的消息，因此不需要回复消息
						//发送消息给管理员
						String result=WxbService.deletePuser(fromUserName);
						System.out.println("修改Puser的deleteFlag状态返回值："+result);
						
						textMessage.setToUserName("oWb37jvyMD4SLsCnsYE9rscUx2vo");
						textMessage.setContent("有一个id为："+fromUserName+"取消了关注！");
						//String returnmsg = DataAccessUtil.pushWeiXinMessage(textMessage);	//不要发送
						return "";
					}else if (eventType.equals(MessageUtil.EVENT_TYPE_SCAN)){
						//这里扫码有代言，也有绑定车型
						String EventKey = requestMap.get("EventKey");
						System.out.println("EventKey===="+EventKey);
						if(EventKey.contains("-")){
							String[] arr = EventKey.split("-");
							
							AppStation appStation = CommonService.getAppStation(null,toUserName);
							if(appStation != null){
								String appsecret = CommonService.getappsercet(appStation.getWxAppId());
								String accessToken = CommonService.getToken(appStation.getWxAppId(),appsecret);
								SNSUserInfo snsUser = AdvancedUtil.getSNSUserInfo(accessToken, fromUserName);
								String userName = EmojiFilter.filterEmoji(snsUser.getNickname());
								if("vin".equals(arr[0])){
									CarModel carModel = SearchService.getCarModelByVIN(arr[1]);
									CommonService.saveUserAndCar(userName, userName, fromUserName, appStation.getWxAppId(), carModel.getMid()+"", arr[1], 
											carModel.getOnMarketYear(), carModel.getOnMarketMonth(), carModel.getBrandName(), carModel.getVehicleSystem(), carModel.getBrandName()+" "+carModel.getVehicleSystem(), 
											carModel.getBrandName()+" "+carModel.getOnMarketMonth()+"年"+carModel.getOnMarketMonth()+"月 "+carModel.getTransmissionDesc()+" "+carModel.getExhaustVolume());
									respContent = "恭喜您，你通过VIN："+arr[1]+"绑定车型成功，赶快点击下面菜单享受服务吧！";
									//判断用户是否存在，不存在则创建
								}else if("car".equals(arr[0])){
									//通过车型id扫码绑定车型
									//通过车型id扫码绑定车型
									CarModel carModel = SearchService.getCarModelByMid(arr[1]);
									CommonService.saveUserAndCar(userName, userName, fromUserName, appStation.getWxAppId(), carModel.getMid()+"", arr[1], 
											carModel.getOnMarketYear(), carModel.getOnMarketMonth(), carModel.getBrandName(), carModel.getVehicleSystem(), carModel.getBrandName()+" "+carModel.getVehicleSystem(), 
											carModel.getBrandName()+" "+carModel.getOnMarketMonth()+"年"+carModel.getOnMarketMonth()+"月 "+carModel.getTransmissionDesc()+" "+carModel.getExhaustVolume());
									respContent = "恭喜您，你通过选择车型："+carModel.getBrandName()+" "+carModel.getVehicleSystem()+"绑定车型成功，赶快点击下面菜单享受服务吧！";
									
								}else if("emp".equals(arr[0])){
									String empId = arr[1];
									WxbService.savePemployeeById(empId, appStation.getWxAppId(), fromUserName);
									respContent = "绑定发送服务消息成功！";
								}else if("msg".equals(arr[0])){
									String userId = arr[1];
									WxbService.saveUserOpenId(userId, fromUserName);
									respContent = "绑定接受服务消息成功！";
								}
							}
						}else if(EventKey.equals("EMPREG")){	//F6 portal员工注册
							respContent = "请点击<a href='http://121.40.65.65:9010/toEmpRegister?openId="+fromUserName+"'>进行员工注册</a>";
						}else if(EventKey.equals("WXADD")){	//F6 portal意向客户添加
							respContent = "请点击<a href='http://121.40.65.65:9010/toWeiXinAddIntentMember?openId="+fromUserName+"'>意向客户添加</a>";
						}else if(EventKey.equals("MBWX")){	//会员店微信验证
							respContent = "请点击<a href='http://121.40.65.65:9010/validateMemberWeiXin?openId="+fromUserName+"'>会员店微信验证</a>";
						}else if(EventKey.equals("KSWX")){	//中心站微信验证
							respContent = "请点击<a href='http://121.40.65.65:9010/validateKsWeiXin?openId="+fromUserName+"'>中心站微信验证</a>";
						}else{
							Puser puser = CommonService.getPuserById(EventKey);
							//获得扫描传的值，该值为谁传过来的openIdx
							//判断fromUserName是否存在puser中
							String appsecret = CommonService.getappsercet(puser.getWxAppId());
							
							String accessToken = CommonService.getToken(puser.getWxAppId(),appsecret);
							SNSUserInfo snsUser = AdvancedUtil.getSNSUserInfo(accessToken, fromUserName);
							if(snsUser != null){
								boolean judgePuser = CommonService.judgePuser(puser.getWxAppId(), fromUserName);
								System.out.println("该用户是否存在："+judgePuser);
								if(!judgePuser){
									//则存储
									CommonService.savePuserForId(snsUser.getNickname(), snsUser.getNickname(), fromUserName, puser.getWxAppId(), snsUser.getHeadImgUrl());
									//判断是否已经存在用户分享表里了
									boolean judgeAuserFenxiang = CommonService.judgeAuserFenxiang(puser.getWxOpenId(), fromUserName, puser.getWxAppId());
									if(!judgeAuserFenxiang){
										//存储该信息
										CommonService.saveAuserFenxiang(puser.getWxOpenId(), fromUserName, puser.getWxAppId(),snsUser.getHeadImgUrl());
									}
								}
							}
							AppStation appStation = CommonService.getAppStation(puser.getWxAppId(),null);
							System.out.println("appStation is==="+appStation);
							respContent = "您已关注["+appStation.getAppName()+"]，点击菜单中的“我要代言”可生成二维码转发到朋友圈等或发送给好友邀请朋友关注。";
						}
					}
					else{
						System.out.println("这里是显示什么呢？");
						return "";
					}
					// 自定义菜单点击事件
				}else{
					System.out.println("其他的文件！！！！");
				}
				
			}else{
				respContent = "谢谢您的惠顾！";
			}
			textMessage.setContent(respContent);
			respMessage = MessageUtil.textMessageToXml(textMessage);*/
			
		/*} catch (Exception e) {
			e.printStackTrace();
		}*/
		
		return null;
					}
		
		
	
		
    /** 
     * emoji表情转换(hex -> utf-16) 
     *  
     * @param hexEmoji 
     * @return 
     */  
    public static String emoji(int hexEmoji) {  
        return String.valueOf(Character.toChars(hexEmoji));  
    }
    
    /** 
     * 主菜单
     *  
     * @return 
     */  
    public static String getMain() {  
        StringBuffer buffer = new StringBuffer();  
        buffer.append("您好，我是小猫，请回复数字选择服务：").append("\n\n");  
        buffer.append("1 购物中心").append("\n\n");  
        buffer.append("2 排名查询").append("\n\n");  
        buffer.append("3 客流量").append("\n\n");  
        buffer.append("4 天气预报").append("\n\n");
        buffer.append("5 公交查询").append("\n\n"); 
        buffer.append("6 周边搜索").append("\n\n");
        buffer.append("7 电影排行榜").append("\n\n"); 
        buffer.append("8 歌曲点播").append("\n\n");
        buffer.append("9 人脸识别").append("\n\n");
        buffer.append("回复“0”显示主菜单");  
        return buffer.toString();  
    }
    
    /** 
     * 购物中心使用指南 
     *  
     * @return 
     */  
    public static String getMallHelp() {  
        StringBuffer buffer = new StringBuffer();  
        buffer.append("购物中心操作指南").append("\n\n");  
        buffer.append("指定关键词搜索").append("\n"); 
        buffer.append("格式：mall+购物中心名称").append("\n");  
        buffer.append("例如：mall新中关、新中关mall").append("\n"); 
        buffer.append("格式：mall+城市名称").append("\n");  
        buffer.append("或者：mall北京、北京mall").append("\n\n");  
        buffer.append("回复“0”显示主菜单");  
        return buffer.toString();  
    } 
    
    /** 
     * 歌曲点播使用指南 
     *  
     * @return 
     */  
    public static String getUsage() {  
        StringBuffer buffer = new StringBuffer();  
        buffer.append("歌曲点播操作指南").append("\n\n");  
        buffer.append("回复：歌曲+歌名").append("\n");  
        buffer.append("例如：歌曲存在").append("\n");  
        buffer.append("或者：歌曲存在@汪峰").append("\n\n");  
        buffer.append("回复“0”显示主菜单");  
        return buffer.toString();  
    }  
    
    public static String getUsageImage() {  
        StringBuffer buffer = new StringBuffer();  
        buffer.append("人脸识别操作指南").append("\n\n");  
        buffer.append("请上传一张带有人脸的图片").append("\n"); 
        buffer.append("回复“0”显示主菜单");  
        return buffer.toString();  
    }
    
    public static void main(String[] args){
    }
}  